﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace SurehealthForms.CashierLogin
{
    public partial class CashierInit : Form
    {
        public CashierInit()
        {
            InitializeComponent();
        }

        #region local variables
        List<perscriptionItem> ItemList = new List<perscriptionItem>();
        byte currentItemNumber = 1;
        byte itemcount;
        #endregion

        /// <summary>
        /// Getting Number of Items and Converting to Double
        /// </summary>
        /// <returns></returns>
        private double numberOfItems()
        {
            double newNoOfItems;
            if (noOfItems.Text == String.Empty)
            {
                newNoOfItems = 0;
            }
            else
            {
                newNoOfItems = double.Parse(noOfItems.Text);
            }
            return newNoOfItems;
        }

        /// <summary>
        ///  Save an order 
        /// </summary>
         private bool SaveAnOrder()
        {
            try
            {
                string OrderID = generateorderID();
                string filename = OrderID + ".Xml";

                itemcount = byte.Parse(noOfItems.Text);
                XmlTextWriter Writer;
                Writer = new XmlTextWriter(filename, Encoding.ASCII);
                Writer.Formatting = Formatting.Indented;
                Writer.WriteStartDocument();

                Writer.WriteStartElement("Prescription");
                Writer.WriteAttributeString("Name", textBox4.Text.ToLower());
                Writer.WriteAttributeString("Doctor", textBox1.Text.ToUpper());
                Writer.WriteAttributeString("Date", dateTimePicker1.Text);
                Writer.WriteAttributeString("NumberofItems", itemcount.ToString());
                Writer.WriteAttributeString("FullDiscount", checkBox1.CheckState.ToString());

                //foreach (perscriptionItem I in ItemList)
                for (int i = 1; i <= itemcount; i++)
                {
                    Writer.WriteStartElement("PrescriptionITEM");
                    Writer.WriteAttributeString("ItemNo", ItemList[i].ItemNumber);
                    Writer.WriteAttributeString("Quantity", ItemList[i].Quantity);
                    Writer.WriteAttributeString("SItem", ItemList[i].Item);
                    Writer.WriteAttributeString("Notes", ItemList[i].Description);
                    Writer.WriteEndElement();
                }
         
                Writer.WriteEndElement();
                Writer.WriteEndDocument();
                Writer.Close();

                List<string> _TempAvailablePrescriptions = new List<string>();
                StreamReader READER = new StreamReader("AvailablePrescriptions.txt");
                while (READER.EndOfStream == false)
                {
                    _TempAvailablePrescriptions.Add(READER.ReadLine());
                }

                READER.Close();
                READER.Dispose();
                _TempAvailablePrescriptions.Add(OrderID);

                StreamWriter WRITER = new StreamWriter("AvailablePrescriptions.txt");
                foreach (string S in _TempAvailablePrescriptions)
                {
                    WRITER.WriteLine(S);
                }
                WRITER.Close();
                WRITER.Dispose();
                return true;

            }
            catch
            {
                return false;
            }


        }
        
        /// <summary>
        /// creates a new order id 
        /// </summary>
        /// <returns>a new order id</returns>
        private string generateorderID()
         {
            #region instance based variables
             string filename ="OrderIDs.txt";
            string NewOrderID = "";
            string LastOrder;
            int LastOrderInt;
             #endregion

            #region readercode
            try
            {
                StreamReader reader = new StreamReader(filename);
                LastOrderInt = int.Parse(LastOrder = reader.ReadLine());
                reader.Close();
                reader.Dispose();
            }
            catch
            {
                StreamWriter writerbackup = new StreamWriter(filename);
                writerbackup.WriteLine("0");
                writerbackup.Close();
                writerbackup.Dispose();
                LastOrderInt = 0;
            }
            #endregion

            LastOrderInt++;

            #region writercode
            StreamWriter writer = new StreamWriter(filename);
            writer.WriteLine(LastOrderInt);
            writer.Close();
            writer.Dispose();
            #endregion

            NewOrderID = LastOrderInt.ToString();
            return NewOrderID;           
        }

        /// <summary>
        /// activates when the next item button is clicked and will
        /// create a new class if it requires a new item
        /// and add it to the list to be wrote.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NextItem_Click(object sender, EventArgs e)
        {
            int numbOfItems= int.Parse(noOfItems.Text);
            if (currentItemNumber < numbOfItems)
            {
                try
                {
                    ItemList[currentItemNumber] = new perscriptionItem(currentItemNumber.ToString(), StockList.SelectedIndex.ToString(), textBox2.Text.ToString(),
                                                               StockList.SelectedItem.ToString(), textBox5.Text.ToString());

                    currentItemNumber++;
                    label1.Text = currentItemNumber.ToString() + "/" + noOfItems.Text;

                    
                }
                catch
                {
                    MessageBox.Show("you need to select a Item");
                }

                if (ItemList[currentItemNumber].ItemNumber == null)
                {
                    textBox2.Text = "";
                    StockList.SelectedIndex = -1;
                    textBox5.Text = "";
                }
                else
                {
                    textBox2.Text = ItemList[currentItemNumber].Quantity.ToString();
                    StockList.SelectedIndex = int.Parse(ItemList[currentItemNumber].ItemIndex);
                    textBox5.Text = ItemList[currentItemNumber].Description;
                }
                NextPreviousButtons();

            }
            else
                MessageBox.Show("You can't enter any more items");  
            
        }

        private void NextPreviousButtons()
        {
            int numbOfItems=0;
            try
            {
               numbOfItems = int.Parse(noOfItems.Text);
            }
            catch
            {
                Console.WriteLine("Error");
                //MessageBox.Show("Error");
            }

            if (numbOfItems == 1)
            {
                PreviousItem.Enabled = false;
                NextItem.Enabled = false;
            }
            else
            {
                if (currentItemNumber == 1)
                {
                    NextItem.Enabled = true;
                    PreviousItem.Enabled = false;
                }
                else
                {
                    if (currentItemNumber == numbOfItems)
                    {
                        NextItem.Enabled = false;
                        PreviousItem.Enabled = true;
                    }

                    if (currentItemNumber < numbOfItems)
                    {
                        PreviousItem.Enabled = true;
                        NextItem.Enabled = true;
                    }
                }
            }
        }

        /// <summary>
        /// Can go back through the list of items added to the perscription for ammendments
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PreviousItem_Click(object sender, EventArgs e)
        {

            int numbOfItems = int.Parse(noOfItems.Text);

            try
            {
                ItemList[currentItemNumber] = new perscriptionItem(currentItemNumber.ToString(), StockList.SelectedIndex.ToString(), textBox2.Text.ToString(),
                                           StockList.SelectedItem.ToString(), textBox5.Text.ToString());

                currentItemNumber--;
                label1.Text = currentItemNumber.ToString() + "/" + noOfItems.Text; 
            }
            catch
            {
                MessageBox.Show("you need to select a Item");
            }

            if (ItemList[currentItemNumber].ItemNumber == null)
            {
                textBox2.Text = "";
                StockList.SelectedIndex = -1;
                textBox5.Text = "";
            }
            else
            {
                textBox2.Text = ItemList[currentItemNumber].Quantity.ToString();
                StockList.SelectedIndex = int.Parse(ItemList[currentItemNumber].ItemIndex);
                textBox5.Text = ItemList[currentItemNumber].Description;
            }

            NextPreviousButtons();
        }


        private void StroreOrder_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// check if there is an XML file for the doctor if not then confirm they want to create one,
        /// if they do, make a file for the doctor and .txt file that will hold a patient list
        /// then add the patient to the list with their name and Date of birth
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfirmDoc_Click(object sender, EventArgs e)
        {
            bool readerActive = false;
            #region check if the doctor has a file if it does load it up

            if(File.Exists(textBox1.Text.ToUpper() + ".Xml"))
            {
                MessageBox.Show("Dr Confirmed on Record");
                readerActive = true;
            }
            else
            {
                CashierLogin.newDocCon forminstance = new newDocCon(textBox1.Text.ToUpper());
                forminstance.ShowDialog();
            }
            #endregion       
            if (readerActive)
            {

                List<string> tempPatientList = new List<string>();

                #region reading the old list
                StreamReader reader = new StreamReader(textBox1.Text.ToUpper() + "patients.txt");
                while (reader.EndOfStream == false)
                {
                    tempPatientList.Add(reader.ReadLine());
                }
                reader.Close();
                reader.Dispose();
                #endregion

                #region check if new patient
                bool newpatient = true;
                foreach (string S in tempPatientList)
                {

                    if (S != (textBox4.Text.ToLower() + dateTimePicker2.Text.ToString()))
                    {
                        newpatient = true;
                    }
                    else
                    {
                        newpatient = false;
                    }

                }
                #endregion

                if (newpatient == true)
                #region update file with new patient
                {
                    tempPatientList.Add(textBox4.Text.ToLower() + dateTimePicker2.Text.ToString());
                    StreamWriter writer = new StreamWriter(textBox1.Text.ToUpper() + "patients.txt");
                    foreach (string S in tempPatientList)
                    {
                        writer.WriteLine(S);
                    }
                    writer.Close();
                    writer.Dispose();
                }
                #endregion

            }
 
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void CashierInit_Load(object sender, EventArgs e)
        {
            foreach(object o in DodgyBobStockControl.Stock.StockList())
            {
                StockList.Items.Add(o);
            }

            for (int i = 0; i < 9; i++)
			{
                ItemList.Add(new perscriptionItem() );
			}
            
        }

        private void noOfItems_TextChanged(object sender, EventArgs e)
        {
            int numbOfItems=0;
            if (noOfItems.Text != "")
            {
                try
                {
                    numbOfItems= int.Parse(noOfItems.Text);
                    if (!(numbOfItems <= 8))
                    {
                        MessageBox.Show("You can not have more than 8 items");
                        noOfItems.Text = "";
                    }
                    else if (numbOfItems < 0)
                    {
                        MessageBox.Show("You can't enter a minus number");
                        noOfItems.Text = "";
                    }
                    else if (numbOfItems == 0)
                    {
                        MessageBox.Show("You can't enter zero");
                        noOfItems.Text = "";
                    }
                    else
                    {
                        if (numbOfItems == 1)
                            NextItem.Enabled = false;
                        else
                            NextItem.Enabled = true;
                    }

                }
                catch
                {
                    MessageBox.Show("You must enter a number");
                }

            }
            
        }

        /// <summary>
        /// stores the order in the system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StoreOrder_Click(object sender, EventArgs e)
        {
            try
            {
                                    ItemList[currentItemNumber] = new perscriptionItem(currentItemNumber.ToString(), StockList.SelectedIndex.ToString(), textBox2.Text.ToString(),
                                                               StockList.SelectedItem.ToString(), textBox5.Text.ToString());

                if (!SaveAnOrder())
                    MessageBox.Show("Failed to save");
                else
                {

                    MessageBox.Show("Successfully Saved order");

                    textBox1.Text = "";
                    textBox4.Text = "";
                    noOfItems.Text = "";
                    dateTimePicker1.Value = DateTime.Today;
                    dateTimePicker2.Value = DateTime.Today;
                    currentItemNumber = 1;
                    label1.Text = currentItemNumber.ToString();
                    textBox2.Text = "";
                    StockList.SelectedIndex = -1;
                    textBox5.Text = "";
                    
                    ItemList.Clear();

                    NextPreviousButtons();
                }
            }
            catch
            {
                MessageBox.Show("Failed to save");
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!AdminAddUserForm.safetycheck(textBox1.Text))
                MessageBox.Show("You broke the core again");

            if (textBox1.Text != "")
                ConfirmDoc.Enabled = true;
            else
                ConfirmDoc.Enabled = false;
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            if (!AdminAddUserForm.safetycheck(textBox4.Text))
                MessageBox.Show("Only Alphabetical characters can be entered.");
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!(textBox2.Text == ""))
                {
                    int Quanity = int.Parse(textBox2.Text);
                    if (Quanity < 0)
                        MessageBox.Show("You can't have a minus number");
                    if (Quanity == 0)
                        MessageBox.Show("You can't have Zero");
                }
                    
            }
            catch
            {
                MessageBox.Show("Stop breaking it!!");
            }
        }
    }
}
